<?php
namespace Plu\Library\Models\Platform\Media;

use Phalcon\Mvc\Model,
    Phalcon\Db\Column,
    Phalcon\Mvc\Model\Resultset\Simple as Resultset;

class Media extends Model {
    public $MediaId;
    public $RoomId;                 
    public $Domain;                  
    public $RoomName;                 
    public $TotalViews;          
    public $TotalComments;           
    public $RecentViews;           
    public $RecentComments;           
    public $RecentViewsUpdateTime;
    public $RecentCommentsUpdateTime;
    public $GameId;
    public $OriginalUrl;
    public $Title;             
    public $Cover;                   
    public $FlashUrl;                 
    public $TimeSpan;                
    public $Desc;                
    public $IsBulletScreen;
    public $CreateUser;          
    public $CreateTime;              
    public $UpdateUser;              
    public $UpdateTime;              
    public $DeleteUser;               
    public $DeleteTime;               
    public $DeleteFlag;               
    public $First7DaysViews;          
    /**
     * 1 tencent 2 other
     */
    public $MediaSource;         
    public $OverallScore;            
    public $MasterTotalScore;         
    public $MasterScore;        
    public $FunTotalScore;            
    public $FunScore;           
    public $TeachTotalScore;          
    public $TeachScore;         
    /**
     * 评分人数
     */
    public $ScoreCount;

    /// <summary>
    /// 评分类型（1高手 2搞笑 3教学）
    /// </summary>
    public $ScoreType;

    public $ExamineStatus;            
    public $ExamineError;           
    public $WCSCloudMediaId;          
    /**
     * 清晰度 1080 720
     */
    public $Definition;

    const query_media_match_tag_v3 = "SELECT m.*
        FROM Media AS m 
        LEFT JOIN TagOfMedia AS tm ON (m.MediaId = tm.MediaId)
        WHERE %s
        GROUP BY m.MediaId 
        HAVING COUNT(1) %s %d
        ORDER BY %s
        LIMIT %d, %d";

    const query_count_match_tag_v3 = "SELECT COUNT(1) as sumatory FROM (
        SELECT 1 FROM Media AS m 
        LEFT JOIN TagOfMedia AS tm ON (m.MediaId = tm.MediaId)
        WHERE %s
        GROUP BY m.MediaId HAVING COUNT(1) %s %d) AS T";

    //http://git.corp.plu.cn/pluplatform/plu/blob/master/Domain/Plu.Platform.Domain/Enums.cs#L5
    const SortTypes = array(
        'top', //最近7天访问量
        'views', //最多播放
        'most', //同views
        'newest',//最新上传
        'comments', //点播数,
        'recentviews',//同top
    );

    const ExamineStatus = array(
        //all
        'all'           => -1,
        //初始
        'None'          => 0,
        //转码
        'TransCoding'   => 1,
        //审核中
        'Examine'       => 2,
        //未通过
        'Refuse'        => 3,
        //通过
        'Pass'          => 4,
        //已删除
        'Deleted'       => 5,
        //待复核
        'Review'        => 6
    );

    public function initialize() {
        $this->setReadConnectionService('db.LongzhuMediaReadOnly');
        $this->setWriteConnectionService('db.LongzhuMedia');
        //$this->belongsTo('RoomId', 'Plu\Library\Models\Platform\Rooms\Room', 'RoomId', array( 'alias' => 'Room' ));
    }

    public function getSource() {
        return 'Media';
    }

    public static function getItem($mediaId) {
        $item = self::findFirst(array(
            "MediaId = :mediaId: AND DeleteFlag = 0",
            "bind" => array(
                "mediaId" => $mediaId
            ),
            "bindTypes" => array(
                "mediaId" => Column::BIND_PARAM_INT
            )
        ));

        return $item;
    }

    public static function getUStreamVideo($mediaId) {
        $item = self::findFirst(array(
            "MediaId = :mediaId: AND DeleteFlag = 1 AND MediaSource = 4",
            "bind" => array(
                "mediaId" => $mediaId
            ),
            "bindTypes" => array(
                "mediaId" => Column::BIND_PARAM_INT
            )
        ));

        return $item;
    }

    public static function getVideosByIds($ids) {
        if (!is_array($ids)) {
            $ids = array($ids);
        }

        $sql = array();
        $len = count($ids);
        $bind = array();
        $bindTypes = array();

        for ($c = 0; $c < $len; $c++) {
            $p = "v{$c}";
            $sql[] = " MediaId = :{$p}: ";
            $bind[$p] = $ids[$c];
            $bindTypes[$p] = Column::BIND_PARAM_INT;
        }

        $sql = '(' . join(' OR ', $sql) . ')';
        $sql .= " AND DeleteFlag = 0";

        $videos = self::find(array(
            $sql,
            'bind' => $bind,
            'bindTypes' => $bindTypes
        ));
        $videos = $videos->toArray();

        $items = array_combine(array_column($videos, 'MediaId'), $videos);
        return $items;
    }

    /**
     * 根据tag数据进行查询
     * :TODO
     */
    //public function getVideosByTags($tags = array(), $strict = true, $roomIds = array(), $gameIds = array(), $start_index = 0, $max_results = 50, $sort_by = 'top', $create_after = "") {
    //    $sql = array();

    //    $bind = array();
    //    $bindTypes = array();


    //    //生成SQL语句
    //    $sql = join(' AND ', $sql);

    //    $connection = $this->getReadConnection();

    //    //总数据
    //    $phql = sprintf(self::query_count_match_tag_v3, $sql, $strict ? '=' : '>', $strict ? count($tags) : 0);
    //    $items = new Resultset(null, $this, $this->getReadConnection()->query($phql, $bind, $bindTypes));
    //    $totalCount = $items->toArray()[0]['sumatory'];

    //    $phql = sprintf(self::query_media_match_tag_v3, $sql, $strict ? '=' : '>', $strict ? count($tags) : 0, $orderby, $start_index, $max_results);
    //    $videos = new Resultset(null, $this, $this->getReadConnection()->query($phql, $bind, $bindTypes));

    //    return array($totalCount, $videos->toArray());
    //}

    public function getVideos($roomIds = array(), $excludeRoomIds = array(), $gameIds = array(), $excludeGameIds = array(), $mediaIds = array(), $excludeMediaIds = array(), $tags = array(), $strict = true, $start_index = 0, $max_results = 50, $sort_by = 'top', $create_after = "-365 days", $source = 0, $hasDelete = false, $duration = 0, $examineStatus = 4) {

        $sql = array();
        $bind = array();
        $bindTypes = array();

        //房间
        if (!empty($roomIds)) {
            $subsql = array();
            $len = count($roomIds);

            for ($c = 0; $c < $len; $c++) {
                $p = "r{$c}";
                $subsql[] = " RoomId = :{$p}: ";
                $bind[$p] = $roomIds[$c];
                $bindTypes[$p] = Column::BIND_PARAM_INT;
            }
            $sql[] = '(' . join(' OR ', $subsql) . ')';
        }


        if (!empty($excludeRoomIds)) {
            $subsql = array();

            //这里会把含有roomid的剔除
            $excludeRoomIds = array_diff($excludeRoomIds, $roomIds);
            $len = count($excludeRoomIds);
            for ($c = 0; $c < $len; $c++) {
                $p = "nr{$c}";
                $subsql[] = " RoomId != :{$p}: ";
                $bind[$p] = $excludeRoomIds[$c];
                $bindTypes[$p] = Column::BIND_PARAM_INT;
            }
            if (count($subsql)) {
                $sql[] = '(' . join(' OR ', $subsql) . ')';
            }
        }

        //游戏
        if (!empty($gameIds)) {
            $subsql = array();
            $len = count($gameIds);

            for ($c = 0; $c < $len; $c++) {
                $p = "g{$c}";
                $subsql[] = " GameId = :{$p}: ";
                $bind[$p] = $gameIds[$c];
                $bindTypes[$p] = Column::BIND_PARAM_INT;
            }
            $sql[] = '(' . join(' OR ', $subsql) . ')';
        }


        if (!empty($excludeGameIds)) {
            $subsql = array();

            //这里会把含有roomid的剔除
            $excludeGameIds = array_diff($excludeGameIds, $gameIds);
            $len = count($excludeGameIds);
            for ($c = 0; $c < $len; $c++) {
                $p = "ng{$c}";
                $subsql[] = " GameId != :{$p}: ";
                $bind[$p] = $excludeGameIds[$c];
                $bindTypes[$p] = Column::BIND_PARAM_INT;
            }
            if (count($subsql)) {
                $sql[] = '(' . join(' OR ', $subsql) . ')';
            }
        }

        //视频id
        if (!empty($mediaIds)) {
            $subsql = array();
            $len = count($mediaIds);

            for ($c = 0; $c < $len; $c++) {
                $p = "m{$c}";
                $subsql[] = " MediaId = :{$p}: ";
                $bind[$p] = $mediaIds[$c];
                $bindTypes[$p] = Column::BIND_PARAM_INT;
            }
            $sql[] = '(' . join(' OR ', $subsql) . ')';
        }


        if (!empty($excludeMediaIds)) {
            $subsql = array();

            //这里会把含有roomid的剔除
            $excludeMediaIds = array_diff($excludeMediaIds, $mediaIds);
            $len = count($excludeMediaIds);
            for ($c = 0; $c < $len; $c++) {
                $p = "nm{$c}";
                $subsql[] = " MediaId != :{$p}: ";
                $bind[$p] = $excludeMediaIds[$c];
                $bindTypes[$p] = Column::BIND_PARAM_INT;
            }
            if (count($subsql)) {
                $sql[] = '(' . join(' OR ', $subsql) . ')';
            }
        }

        //必须非删除的
        if (!$hasDelete) {
            $sql[] = "DeleteFlag = 0";
        }

        //duration
        if ($duration > 0) {
            $sql[] = "TimeSpan > :duration:";
            $bind['duration'] = $duration;
            $bindTypes['duration'] = Column::BIND_PARAM_INT;
        }

        //过滤视频来源
        if ($source > 0) {
            $sql[] = "MediaSource = :source:";
            $bind['source'] = $source;
            $bindTypes['source'] = Column::BIND_PARAM_INT;
        }

        //过滤视频审核状态 默认只显示审核通过的
        if ($examineStatus > -1) {
            $sql[] = "ExamineStatus = :examine:";
            $bind['examine'] = $examineStatus;
            $bindTypes['examine'] = Column::BIND_PARAM_INT;
        }

        $orderby = "";
        switch ($sort_by) {
            case "top":
            case "recentviews":
                $create_after = date('Y-m-d', strtotime($create_after));
                $sql[] = " CreateTime > '$create_after' ";
                $orderby = " RecentViews DESC ";
                break;
            case "views":
            case "most":
                $orderby = " TotalViews DESC ";
                break;
            case "comments":
                $orderby = " TotalComments DESC ";
                break;
            case "newest":
            default:
                $orderby = " MediaId DESC ";//按时间排序
                break;
        }




        //tags
        if (!empty($tags)) {
            $subsql = array();
            $len = count($tags);

            for ($c = 0; $c < $len; $c++) {
                $p = "ttg{$c}";
                $subsql[] = " TagId = :$p: ";
                $bind[$p] = $tags[$c];
                $bindTypes[$p] = Column::BIND_PARAM_STR;
            }
            $sql[] = '(' . join( ' OR ', $subsql) . ')';

            $sql = join(' AND ', $sql);
            
            $connection = $this->getReadConnection();

            //总数据
            $phql = sprintf(self::query_count_match_tag_v3, $sql, $strict ? '=' : '>', $strict ? count($tags) : 0);
            $c = $connection->convertBoundParams($phql, $bind);
            $phql = $c['sql'];
            $_bind = $c['params'];
            $items = new Resultset(null, $this, $this->getReadConnection()->query($phql, $_bind));
            $totalCount = $items->toArray()[0]['sumatory'];

            $phql = sprintf(self::query_media_match_tag_v3, $sql, $strict ? '=' : '>', $strict ? count($tags) : 0, $orderby, $start_index, $max_results);
            $c = $connection->convertBoundParams($phql, $bind);
            $phql = $c['sql'];
            $_bind = $c['params'];

            $videos = new Resultset(null, $this, $this->getReadConnection()->query($phql, $_bind));

            return array($totalCount, $videos->toArray());
        } else {
            $sql = join(' AND ', $sql);

            //拼接params
            $params = array(
                $sql,
                'bind' => $bind,
                'bindTypes' => $bindTypes
            );

            //获得总数
            $totalCount = self::count($params);

            $params['offset'] = $start_index;
            $params['limit'] = $max_results;

            $params['order'] = $orderby;

            $videos = self::find($params);

            return array($totalCount, $videos->toArray());
        }
    }
}
